package com.jilijili.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.jilijili.config.mq.RabbitMQConfig;
import com.jilijili.enums.MessageEnum;
import com.jilijili.enums.YesOrNo;
import com.jilijili.exceptions.GraceException;
import com.jilijili.grace.result.GraceJSONResult;
import com.jilijili.grace.result.ResponseStatusEnum;
import com.jilijili.mapper.FansMapper;
import com.jilijili.mapper.FansMapperCustom;
import com.jilijili.mapper.VlogMapper;
import com.jilijili.pojo.Fans;
import com.jilijili.pojo.Users;
import com.jilijili.pojo.Vlog;
import com.jilijili.pojo.mo.MessageMo;
import com.jilijili.pojo.vo.FansVo;
import com.jilijili.pojo.vo.VlogerVo;
import com.jilijili.service.FansService;
import com.jilijili.service.MsgService;
import com.jilijili.service.base.BaseInfoProperties;
import com.jilijili.service.base.PagedGridResult;
import com.jilijili.utils.redis.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @author admin
 * @description 针对表【fans(粉丝表
 * <p>
 * )】的数据库操作Service实现
 * @createDate 2022-03-12 07:11:29
 */
@Service
public class FansServiceImpl extends ServiceImpl<FansMapper, Fans>
        implements FansService {

    @Resource
    private FansMapper fansMapper;

    @Resource
    private RedisOperator redis;

    @Resource
    private FansMapperCustom fansMapperCustom;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MsgService msgService;

    @Resource
    private VlogMapper vlogMapper;

    @Resource
    private Sid sid;


    /**
     * 查询我的粉丝列表
     */
    @Override
    public PagedGridResult queryMyFans(String myId, Integer page, Integer pageSize) {

        IPage<FansVo> fansVoIPage = this.fansMapperCustom.selectJoinPage(new Page<>(page, pageSize), FansVo.class,
                new MPJLambdaWrapper<FansVo>()
                        .selectAs(Users::getId, FansVo::getFanId)
                        .select(Users::getNickname)
                        .select(Users::getFace)
                        .leftJoin(Users.class, Users::getId, Fans::getFanId)
                        .eq(true, Fans::getVlogerId, myId).orderBy(true, false, Users::getNickname));
        // 判断是否互相关注
        for (FansVo record : fansVoIPage.getRecords()) {
            String isFans = this.redis.get(BaseInfoProperties.REDIS_FANS_AND_VLOGGER_RELATIONSHIP + ":" + myId + ":" + record.getFanId());
            record.setFollowed(StringUtils.isNotBlank(isFans) && "1".equalsIgnoreCase(isFans));
        }
        PagedGridResult pagedGridResult = new PagedGridResult();
        pagedGridResult.setRows(fansVoIPage.getRecords());
        pagedGridResult.setPage((int) fansVoIPage.getCurrent());
        pagedGridResult.setTotal(fansVoIPage.getPages());
        pagedGridResult.setRecords(fansVoIPage.getTotal());
        return pagedGridResult;
    }

    /**
     * 查询我关注博主的列表
     */
    @Override
    public PagedGridResult queryMyFollows(String myId, Integer page, Integer pageSize) {

        IPage<VlogerVo> vlogerVoIPage = this.fansMapperCustom.selectJoinPage(new Page<>(page, pageSize), VlogerVo.class,
                new MPJLambdaWrapper<VlogerVo>()
                        .selectAs(Users::getId, VlogerVo::getVlogerId)
                        .select(Users::getNickname)
                        .select(Users::getFace)
                        .leftJoin(Users.class, Users::getId, Vlog::getVlogerId)
                        .eq(true, Fans::getFanId, myId).orderBy(true, false, Users::getNickname));
        PagedGridResult pagedGridResult = new PagedGridResult();
        pagedGridResult.setRows(vlogerVoIPage.getRecords());
        pagedGridResult.setPage((int) vlogerVoIPage.getCurrent());
        pagedGridResult.setTotal(vlogerVoIPage.getPages());
        pagedGridResult.setRecords(vlogerVoIPage.getTotal());

     /*   Map<String, Object> map = new HashMap<>();
        if(!StringUtils.isBlank(myId)){
            map.put("myId",myId);
        }
        List<VlogerVo> vlogerVos = this.fansMapperCustom.queryMyFollows(map);*/

        return pagedGridResult;

    }

    /**
     * 是否关注博主
     */
    @Override
    public boolean queryDoIFollowVloger(String usersId, String vlogerId) {
        Fans fans = this.queryFansRelationship(usersId, vlogerId);
        return !ObjectUtils.isEmpty(fans);
    }


    /**
     * 取消关注
     */
    @Override
    public void doCancel(String myId, String vlogerId) {
        //TODO [1]判断是否 朋友关系
        Fans fans = this.queryFansRelationship(myId, vlogerId);
        if (!ObjectUtils.isEmpty(fans) && fans.getIsFanFriendOfMine().equals(YesOrNo.YES.type)) {
            // [1.2] 抹除双方的朋友关系
            Fans vloger = this.queryFansRelationship(vlogerId, myId);
            vloger.setIsFanFriendOfMine(YesOrNo.NO.type);
            this.fansMapper.updateById(vloger);

        }
        {
            //不是朋友关系
        }
        //TODO [2] 删除 自己的关注记录
        int i = this.fansMapper.deleteById(fans);
        if (i < 0) {
            GraceJSONResult.errorCustom(ResponseStatusEnum.FAILED);
        }

        //取消关注通知
        MessageMo build = MessageMo.builder()
                .fromUserId(myId)
                .toUserId(vlogerId).build();
        this.rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_MSG,
                "routing.sys.msg." + MessageEnum.UN_F0LLOW_Y0U.enValue,
                JSON.toJSONString(build));

    }

    /**
     * 关注
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void doFollow(String myId, String vlogerId) {
        //TODO 我关注 -> 作者
        Fans fans = Fans.builder()
                .id(sid.nextShort()) // 粉丝表id
                .fanId(myId) // 我是粉丝
                .vlogerId(vlogerId).build();// 作者id

        //TODO 是否互相关注
        Fans vloger = this.queryFansRelationship(myId, vlogerId);
        if (!ObjectUtils.isEmpty(vloger)) {
            //设置为互相关注状态
            fans.setIsFanFriendOfMine(YesOrNo.YES.type);

            // 作者更新互相关注状态
            vloger.setIsFanFriendOfMine(YesOrNo.YES.type);
            this.fansMapper.updateById(vloger);
        } else {
            fans.setIsFanFriendOfMine(YesOrNo.NO.type);
            int isInsert = this.fansMapper.insert(fans);
            //TODO 插入操作, 没有关注过
            if (isInsert < 0) {
                GraceException.display(ResponseStatusEnum.FAN_ERROR_EQ_NULL);
            }
        }

        // 关注消息消息
//        msgService.createMsg(myId, vlogerId, MessageEnum.F0LLOW_Y0U.type, null);
        MessageMo build = MessageMo.builder()
                .fromUserId(myId)
                .toUserId(vlogerId).build();
        String json = JSON.toJSONString(build);
        this.rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_MSG,
                "routing.sys.msg." + MessageEnum.F0LLOW_Y0U.enValue
                , json);


    }


    // 查询互相关注关系
    public Fans queryFansRelationship(String fanId, String vlogerId) {
        // 粉丝表查询 是否有我关注博主
        Fans fans = this.fansMapper.selectOne(new LambdaQueryWrapper<Fans>()
                .eq(true, Fans::getFanId, fanId)
                .eq(true, Fans::getVlogerId, vlogerId));

        if (!ObjectUtils.isEmpty(fans)) {
            return fans;
        }
        return null;

    }
}




